<?php
/**
 * 获取类中的所有方法
 * @param $class
 * @return mixed
 */
function get_class_all_methods($class){
    $r = new ReflectionClass($class);
    $method_arr = array();//public 方法列表
    $methods = array();//当前方法信息
    foreach($r->getMethods() as $key=>$methodObj){
        if($methodObj->isPrivate()){
            $methods[$key]['type'] = 'private';
        }elseif($methodObj->isProtected()){
            $methods[$key]['type'] = 'protected';
        }else{
            $methods[$key]['type'] = 'public';
            $method_arr[] =  $methodObj->name;
        }
        $methods[$key]['name'] = $methodObj->name;
        $methods[$key]['class'] = $methodObj->class;
    }
    return $method_arr;
    //return $methods;
}

function e($s){
    echo $s,'<br/>';
}

function d($info = null, $time = false)
{
    if (! DEBUG)
        return;
    static $debug_info = array();
    if ($info != 'get_debug_data')
    {
        $debug_info[] = array('info'=>$info, 'backtrace'=>debug_backtrace());
        if ($time)
            time_debug('debug_time_' . count($debug_info));
    }

    return $debug_info;
}

function time_debug($name = null)
{
    static $start_time;
    if (! $start_time)
        $start_time = microtime(true);
    static $debug_points;
    if (! $debug_points)
        $debug_points = array();
    if (! $name)
        return $debug_points;
    $last_time = $debug_points[count($debug_points)-1]['offset_time'];
    $debug_points[] = array(
        'name'  =>  $name,
        'offset_time'  =>  microtime(true) - $start_time,
        'exec_time'  =>  microtime(true) - $start_time - $last_time,
    );

    return $debug_points;
}
/*
 * 通用日志记录方法(文件方式记录)
 * @param info
 */
function l($info, $file = 'info', $log_type = 'redis')
{
    $debug = debug_backtrace();
    if (count($debug) > 1)
        $debug = $debug[1];
    else
        $debug = $debug[0];

    $time = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'];
    $url = $_SERVER['REQUEST_URI'];
    $file_name = $debug['file'];
    $line = $debug['line'];
    $function = $debug['function'];
    $info = is_string($info) ? $info : var_export($info, true);

    $server_addr = $_SERVER['SERVER_ADDR'];

    if ($log_type == 'file')
    {
        $str = 'Time:' . $time . ', ' .
            'Server:' . $server_addr . ', ' .
            'IP:' . $ip . ', ' .
            'URL:' . $url . ', ' .
            'File:' . $file_name . ', ' .
            'Line:' . $line . ', ' .
            'Function:' . $function . ', ' .
            'Info:' . $info . "\n";
        file_put_contents(LOG_PATH . $file . '.log', $str, FILE_APPEND);
    }
    else if ($log_type == 'redis')
    {
       /* if ($file == 'redis_runtime')
            return;
        $info = array(
            'time'  =>  $time,
            'server'=>  $server_addr,
            'ip'    =>  $ip,
            'url'   =>  $url,
            'file'  =>  $file_name,
            'line'  =>  $line,
            'function'  =>  $function,
            'info'  =>  $info,
        );
        $redis = RedisFactory::getInstance('log');
        $redis->lPush($file, serialize($info));*/
    }
}

function isCli() {
    return PHP_SAPI == 'cli' && empty($_SERVER['REMOTE_ADDR']);
}

function p($info, $exit = true, $ret = false)
{
    if (defined('RUNNING_MODE') && RUNNING_MODE == 'dev') {
        $debug  = debug_backtrace();
        $output = '';

        if (isCli()) {
            $output .= '[TRACE]' . PHP_EOL;
            foreach ($debug as $v) {
                $output .= 'File:' . $v['file'];
                $output .= 'Line:' . $v['line'];
                $output .= 'Args:' . implode(',', $v['args']) . PHP_EOL;
            }
            $output .= '[Info]' . PHP_EOL;
            $output .= var_export($info, true) . PHP_EOL;
        } else {
            foreach ($debug as $v) {
                $output .= '<b>File</b>:' . $v['file'] . '&nbsp;';
                $output .= '<b>Line</b>:' . $v['line'] . '&nbsp;';
                $output .= $v['class'] . $v['type'] . $v['function'] . '(\'';
                $output .= implode('\',\' ', $v['args']);
                $output .= '\')<br/>';
            }
            $output .= '<b>Info</b>:<br/>';
            $output .= '<pre>';
            $output .= var_export($info, true);
            $output .= '</pre>';
        }

        if ($ret)
            return $output;
        else
            echo $output;
        if ($exit)
            exit;
    } else {
        return;
    }
}

function loadModule($module, $params = array())
{
    global $_user, $_session;

    if ($params)
    {
        extract($params);
    }

    $content = '';
    if (file_exists($module_file = MODULE_PATH . $module . '.php'))
    {
        ob_start();
        include $module_file;
        $content = ob_get_contents();
        ob_end_clean();
    }
    return $content;
}


/**
 * 模块加载方法 可以添加换成
 * @param $module
 * @param array $params
 * @return string
 */
function module($module, $params = array())
{
    $content = loadModule($module, $params);

    return $content;
}

function gbk2utf8($data)
{
    if (is_array($data))
    {
        return array_map('gbk2utf8', $data);
    }
    else if (is_object($data))
    {
        return array_map('gbk2utf8', get_object_vars($data));
    }
    return mb_convert_encoding($data, 'UTF-8', 'GBK');
}

function utf8togbk($data)
{
    if (is_array($data))
    {
        return array_map('utf8togbk', $data);
    }
    else if (is_object($data))
    {
        return array_map('utf8togbk', get_object_vars($data));
    }
    return mb_convert_encoding($data, 'GBK','UTF-8');
}
// short function
function ifset($array, $key, $default = null)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

function isUrl($url)
{
    return preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i',$url);
}


//截取中文字符,支持一个英文算两个字符，如果两个英文算一个字的截取传入280即可代表140
function cnSubStr($string,$sublen,$tip='')
{
    $str=' ';
    if(strlen($string)>$sublen){
        for($i=0;$i<$sublen;$i++){
            if(ord(substr($string,$i,1))>0xa0){//0xa0代表中文字符的开始
                if($i+2<strlen($string)){
                    $str.=substr($string,$i,3);
                    $i+=2;
                }
            }else{
                $str.=substr($string,$i,1);
            }
        }
    }else{
        $str=$string;
    }
    return $str.$tip;
}

function curl_get_contents($url, $timeout = 5){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    @curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, true);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 86400); // 缓存一天
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function curl_post_contents($url, $data = array(), $cookiepath = ''){
    $userAgent = 'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)';
    $referer = $url;
    if(!is_array($data) || !$url) return '';
    $post = '';
    foreach($data as $key => $value){
        $post .= $key . '=' . urlencode($value) . '&';
    }
    rtrim($post, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);				//设置访问的url地址
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);				//设置超时
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);	//用户访问代理 User-Agent
    curl_setopt($ch, CURLOPT_REFERER, $referer);		//设置 referer
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);		//跟踪301
    curl_setopt($ch, CURLOPT_POST, 1);					//指定post数据
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);		//添加变量
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiepath);	//COOKIE的存储路径,返回时保存COOKIE的路径
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		//返回结果
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

// gbk的explode，多字节处理，防止5c问题发生
function gbk_explode($l,$s) {
    $s = mb_convert_encoding($s, "utf-8", "GBK");
    $a = explode($l,$s);
    foreach($a as &$v){
        $v = mb_convert_encoding($v, "GBK", "utf-8");
    }
    return $a;
}

//字符串转数组
function stringToArray($str, $sign = '|', $break = ','){
    $arr = gbk_explode($sign, $str);
    if($break){
        foreach($arr as $value) {
            if($value){
                $data[] = explode($break, $value);
            }
        }
    }
    return $break ? $data : $arr;
}

//按照KEY取出数组重复
function array_union_key($a,$b) {
    return array_merge(array_diff_key($a,$b),$b);
}

// array_diff's bug for PHP5.2.6-5.3.3
//比对出 a1中不存与在a2的数组值
function my_array_diff($a1, $a2)
{
    $a2 = array_flip((array)$a2);
    foreach ((array)$a1 as $key => $item)
    {
        if (isset($a2[$item]))
        {
            unset($a1[$key]);
        }
    }
    return $a1;
}

//取得URL的主域名
function is_domain($url){
    $tmp =  parse_url($url);
    $tmp_host = array_reverse(explode('.',$tmp['host']));
    $host_domain = $tmp_host[1].'.'.$tmp_host[0];
    if($host_domain =='whoopsfeed.com')
        return true;
    else
        return false;
}

/**
 * 跳转页面--重定向
 * @param  string $url
 * @param int $status 301 永久跳转 302 暂时跳转
 * @return void
 */
function redirect($url, $status = 302) {
    header('Status: ' . $status);
    header('Location: ' . $url);
    exit();
}

function return_ip()
{
    $ip = "0.0.0.0";
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        $ip_a = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']) ;
        for($i=0;$i<count($ip_a);$i++)
        {
            $tmp = trim($ip_a[$i]) ;
            if($tmp=='unknown'||$tmp=='127.0.0.1'||strncmp($tmp,'10.',3)==0||strncmp($tmp,'172',3)==0||strncmp($tmp,'192',3)==0)
                continue ;
            $ip = $tmp;
            break ;
        }
    }
    else if(!empty($_SERVER['HTTP_CLIENT_IP']))
    {
        $ip = trim($_SERVER['HTTP_CLIENT_IP']);
    }
    else if (!empty($_SERVER['REMOTE_ADDR']))
    {
        $ip = trim($_SERVER['REMOTE_ADDR']);
    }

    return $ip;
}

/**
 * 判读是否是 Ajax 请求
 * @return boolean
 */
function isAjax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');
}

/**
 * 过虑HTML
 * @param  string $var
 * @return string
 */
function htmlFilter($var) {
    $search = array (
        "'<script[^>]*?>.*?<\/script>'si",
        "'<html[^>]*?>.*?<body[^>]*?>'si",
        "'<\/body>.*?<\/html>'si",
        "'<style[^>]*?>.*?<\/style>'si",
        "'<link[^>]*?\s*[\/]?>'si",
        "'<iframe[^>]*?>.*?<\/iframe>'si",
        "'<form[^>]*?>(.*?)<\/form>'si",
        "'<textarea[^>]*?>.*?<\/textarea>'si",
        //"'\s*id\s*=\s*[\"|\'].*?[\"|\']'si",
        //"'\s* clas\s*s\s*=\s*[\"|\'].*?[\"|\']'si",
        //"'<!--.*?-->'si",
    );
    $replace = array ('', '', '', '', '', '', '', '', '', '', '');
    $var = preg_replace ($search, $replace, $var);
    $trans = array(
        '?' => '&#63;',
        '\\' => '&#92;',
        '`'=>'',
    );
    return strtr($var, $trans);
}

/*
 * 对二维数组,按第二维数组中的某个键值对进行排序
 * @param array $arr 二维数组如 array('0'=> array('v_title' => '视频2','v_image'=>'地址2','v_sort'=>'2'),'1'=>array('v_title' => '视频1','v_image'=>'地址1','v_sort'=>'1'))
 * @param string 二维数组中的某个键值对 如（v_sort）
 * @param int $sort_flags 排序方式 0:升序，1:降序
 * @return array 排序后的数二维数组
 * @date 2011-09-22
 * @ + 增加一个排序方式，
 */
function array_sort($arr,$field,$sort_flags =0){
    $sort_tmp =array();
    $arr_tmp  =array();
    foreach($arr as $key=>$value){
        $sort_tmp[$key]=$value[$field];//取出排列顺序字段
    }
    asort($sort_tmp);//按值排序，保留键的对应,可校正排序相同的情况
    foreach($sort_tmp as $k=>$v){
        $arr_tmp[] = $arr[$k] ;
    }
    return $sort_flags ? array_reverse($arr_tmp): $arr_tmp ;
}


/**
 * 处理XML JSON返回格式
 * @param $data
 * @param $format
 * @param string $jsonp
 * @return string
 */
function formatData($data, $format, $jsonp = ""){
    $data = gbk2utf8($data);
    if($format == "json"){
        return json_encode(($data));
    }
    if($format == "xml"){
        $xml= "<?xml version=\"1.0\" encoding=\"utf-8\" ?> ";
        $xml.="<response>";
        $xml.= formatXml($data);
        $xml.="</response>";
        return $xml;
    }
    if ($format =="jsonp" ){
        return $jsonp."('".json_encode($data)."')";
    }
}
/**
 * 处理xml的方法
 * @param $data
 * @return string
 */
function formatXml($data){
    $xml = '';
    foreach($data as $key=>$val){
        $xml.="<{$key}>";
        if(is_array($val)){
            $xml.= formatXml($val);
        }
        else{
            $xml.="{$val}";
        }
        $xml.="</{$key}>";
    }
    return $xml;
}

function toXml($data,$xml_setting=array(),& $xml=null,& $parent_node = null){
    $xml_setting_default = array('root'=>'xml','charset'=>'utf-8','num_key'=>'item','version'=>'1.0');
    $xml_setting         = is_array($xml_setting) ? $xml_setting : array() ;
    $xml_setting         = array_merge($xml_setting_default,$xml_setting);
    if($xml == null){
        $xml               =  new DOMDocument($xml_setting['version'],$xml_setting['charset']);
        $xml->formatOutput = false;
        $parent_node       = $xml->createElement($xml_setting['root']);
        $xml->appendChild($parent_node);
    }
    if($xml == null || $parent_node == null ){
        return false;
    }
    foreach($data as $key => $value){
        $node_name  = is_numeric($key) ? $xml_setting['num_key'] : $key;
        $node       = $xml->createElement($node_name);
        $parent_node->appendChild($node);
        if(!is_array($value)){
            $child_node  = $xml->createTextNode($value);
            $node->appendChild($child_node);
        }else{
            $child_node  = toXml($value,$xml_setting,$xml,$node);
        }

    }
    return $xml->saveXML();
}

//去除空格
function trim_space($s) {
    $s = mb_ereg_replace('^(　| )+', '', $s);
    $s = mb_ereg_replace('(　| )+$', '', $s);
    return $s;
}

//remove page val's url
//@caixudong 增加两个参数，第一个是手动传入的额外参数，第二个是否从URL删除分页参数，默认删除
function parse_cur_url($p = array(),$remove_page = true){

    //base url
    $base_name = basename($_SERVER['SCRIPT_FILENAME']);

    //ex url
//    $tmp_arr = $_GET + $_POST + $p;
    $tmp_arr = array_merge($_GET, $_POST, $p);
    // remove page
    if($remove_page) unset($tmp_arr['page']);
    if($tmp_arr)
        $ex_url = http_build_query($tmp_arr);
    else
        $ex_url = '';

    //full url
    if($ex_url)
        $full_url = $base_name."?".$ex_url;
    else
        $full_url = $base_name;

    return $full_url;
}

//获取HOST
//$_SERVER['HTTP_HOST']在客户的环境里，取得的值总是程序所在的服务器在其局域网内的ip值
//is_url 是否以url的形式返还
function getHttpHost($is_url = true){
    return ($is_url == true ? "http://" : "") .(isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));
}

//创建文件夹
function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;

    if (!mkdirs(dirname($dir), $mode)) return FALSE;

    return @mkdir($dir, $mode);
}

function alert ($msg)
{
    $str = '<script type="text/javascript">alert('.$msg.');</script>';

    echo $str;
}

function create_str( $length = 8, $join_num = false ) {
    // 密码字符集，可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $chars = ($join_num == true ? $chars.'0123456789' : $chars);
    $str = '';
    for ( $i = 0; $i < $length; $i++ )
    {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符；
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
        $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $str;
}

function nameRule(){
    $str1 = create_str();
    $str2 = create_str();
    return md5($str1.time().$str2);
}

//文件上传类的使用
function uploadFile($type = 'focus'){
    $ret_arr = array('code'=>0,'data'=>'');

    $upload_type = array(
        'ad' => array(//推广为图片上传
            'size' => 2,
            'ext' =>  'jpg,gif,png,bmp',
            'rule' => 'nameRule',
            'dir' =>  DOCUMENT_ROOT_PATH . 'Upload/ad/'.date('Y').'/'.date('m').'/'.date('d').'/'
        ),
        'face' => array(//头像图片上传
            'size' => 2,
            'ext' =>  'jpg,gif,png,bmp',
            'rule' => 'nameRule',
            'dir' =>  DOCUMENT_ROOT_PATH . 'Upload/face/'.date('Y').'/'.date('m').'/'.date('d').'/'
        ),
        'focus' => array(//新闻焦点图（列表页用）
            'size' => 2,
            'ext' =>  'jpg,gif,png,bmp',
            'rule' => 'nameRule',
            'dir' =>  DOCUMENT_ROOT_PATH . 'Upload/new/focus/'.date('Y').'/'.date('m').'/'.date('d').'/'
        ),
        'new' => array(//新闻图片（内容页用）
            'size' => 2,
            'ext' =>  'jpg,gif,png,bmp',
            'rule' => 'nameRule',
            'dir' =>  DOCUMENT_ROOT_PATH. 'Upload/new/big/'.date('Y').'/'.date('m').'/'.date('d').'/'
        )
    );
    include COMMON_LIB_PATH . 'Upload.class.php';//后台控制器类

    $upload = new Upload();
    //设置上传文件大小
    $upload->maxSize = (1024 * 1024) * $upload_type[$type]['size']; //最大2M

    switch($type){
        case 'focus':
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb = true;
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix = '';
            //设置缩略图最大宽度
            $upload->thumbMaxWidth = '320';
            //设置缩略图最大高度
            $upload->thumbMaxHeight = '200';
            //删除原图
            //$upload->thumbRemoveOrigin = true;
            break;
        case 'new':
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb = true;
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix = '';
            //设置缩略图最大宽度
            $upload->thumbMaxWidth = '170';
            //设置缩略图最大高度
            $upload->thumbMaxHeight = '112';
            //设置缩略图路径
            $upload->thumbPath =  str_replace('big', 'small', $upload_type[$type]['dir']);
            $upload->autoSub = true;
            $upload->subType = 'no';
            //删除原图
            //$upload->thumbRemoveOrigin = true;
    }

    //设置上传文件类型
    $upload->allowExts = explode(',', $upload_type[$type]['ext']);

    //设置附件上传目录
    $upload->savePath = $upload_type[$type]['dir'];
    $upload->saveRule = $upload_type[$type]['rule'];

    if (!$upload->upload()) {
        //捕获上传异常
        $ret_arr = array('statusCode'=>1,'data'=>$upload->getErrorMsg());
    } else {
        //取得成功上传的文件信息
        $ret_arr = array('statusCode'=>2,'data'=>$upload->getUploadFileInfo());
    }

    return $ret_arr;
}

function content_preg_img($content,$time = null)
{
    $dir_y = date('Y');
    $dir_m = date('m');
    $dir_d = date('d');

    $data_str = $dir_y.'/'.$dir_m.'/'.$dir_d;
    if($time != null){
        $dir_y = date('Y',strtotime($time));
        $dir_m = date('m',strtotime($time));
        $dir_d = date('d',strtotime($time));
        $data_str = $dir_y.'/'.$dir_m.'/'.$dir_d;
    }
    $img_exist = is_int(strpos($content, '<img'));

    $new_content = '';
    if ($img_exist) {
        //取出所有img标签并匹配其链接
        $preImg = "/<[i|I][m|M][g|G].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg|\.jpeg!w3]))[\'|\"].*?[\/]?>/";
        preg_match_all($preImg, $content, $arr); //$content为原始文章内容，下同

        foreach ($arr[1] as $v) {
            //读取图片
            $img = file_get_contents($v);
            //获取图片名
            $picName = pathinfo($v);
            //创建图片文件到本地
            $dir = DOCUMENT_ROOT_PATH. 'Upload/new/big/'.$data_str.'/';
            $file_name = nameRule() . '.' . $picName['extension'];
            $file_name = explode('!',$file_name);
            $file_name = $file_name[0];
            if (!file_exists($dir)) {
                mkdirs($dir,0777);
            }

            $small_dir = str_replace('big', 'small', $dir);
            if (!file_exists($small_dir)) {
                mkdirs($small_dir,0777);
            }

            if(!file_exists($dir . $file_name)){
                file_put_contents($dir . $file_name, $img);
                imagezoom( $dir . $file_name, $small_dir . $file_name,  340, 224, '#FFFFFF' );
            }
            $namePic[] = $dir . $file_name;
        }

        //替换所有图片链接为本地链接
        $new_content = str_replace($arr[1], $namePic, $content); //$con为被替换链接地址之后的文章内容
    } else {
        $new_content = $content;
    }

    return $new_content;
}

/**
 * 显示转换方法 1=》待审核
 * @param $key
 * @param $arr
 * @return string
 */
function changeShow($key,$arr){
    return isset($arr[$key]) ? $arr[$key] :  '未知';
}

/**
 * 文本编辑器使用
 * @param $a
 * @param $b
 * @return int
 */
function cmpNewDirPicture($a, $b) {
    global $order;
    if ($a['is_dir'] && !$b['is_dir']) {
        return -1;
    } else if (!$a['is_dir'] && $b['is_dir']) {
        return 1;
    } else {
        if ($order == 'size') {
            if ($a['filesize'] > $b['filesize']) {
                return 1;
            } else if ($a['filesize'] < $b['filesize']) {
                return -1;
            } else {
                return 0;
            }
        } else if ($order == 'type') {
            return strcmp($a['filetype'], $b['filetype']);
        } else {
            return strcmp($a['filename'], $b['filename']);
        }
    }
}

//分词类调用
function strToTags($str){
    include COMMON_VENDOR_PATH . '/phpanalysis2.0/phpanalysis.class.php';

    PhpAnalysis::$loadInit = false;
    $pa = new PhpAnalysis('utf-8', 'utf-8', false);
    $pa->LoadDict();
    $pa->SetSource($str);
    $pa->StartAnalysis( false );
    $tags = $pa->GetFinallyResult();

    $ret = array();

    if(!empty($tags)){
        $ret = explode(" ",$tags);

        foreach((array)$ret as $k=>$v){
            $is_yes = preg_match("/[\x{4e00}-\x{9fa5}]|[a-zA-Z]/u", $v);
            $is_length = strlen($v);
            if(!$is_yes || $is_length <= 3 || $is_length >21){
                unset($ret[$k]);
            }
        }
    }

    return $ret;
}

//页面信息抓取方法
function crawlHtml($url){
	include COMMON_VENDOR_PATH . '/simplehtmldom_1_5/simple_html_dom.php';
	
	return file_get_html($url);
}


/*
    php缩略图函数：
        等比例无损压缩，可填充补充色 author: 华仔
    主持格式：
        bmp 、jpg 、gif、png
    param:
        @srcimage : 要缩小的图片
        @dstimage : 要保存的图片
        @dst_width: 缩小宽
        @dst_height: 缩小高
        @backgroundcolor: 补充色  如：#FFFFFF  支持 6位  不支持3位
*/
function imagezoom( $srcimage, $dstimage,  $dst_width, $dst_height, $backgroundcolor ) {

    // 中文件名乱码
    if ( PHP_OS == 'WINNT' ) {
        $srcimage = iconv('UTF-8', 'GBK', $srcimage);
        $dstimage = iconv('UTF-8', 'GBK', $dstimage);
    }

    $dstimg = imagecreatetruecolor( $dst_width, $dst_height );
    $color = imagecolorallocate($dstimg, hexdec(substr($backgroundcolor, 1, 2)), hexdec(substr($backgroundcolor, 3, 2)), hexdec(substr($backgroundcolor, 5, 2)));
    imagefill($dstimg, 0, 0, $color);

    if ( !$arr=getimagesize($srcimage) ) {
        return -1;
        exit;
    }

    $src_width = $arr[0];
    $src_height = $arr[1];
    $srcimg = null;
    $method = getcreatemethod( $srcimage );
    if ( $method ) {
        eval( '$srcimg = ' . $method . ';' );
    }

    $dst_x = 0;
    $dst_y = 0;
    $dst_w = $dst_width;
    $dst_h = $dst_height;
    /*
    if ( ($dst_width / $dst_height - $src_width / $src_height) > 0 ) {
        $dst_w = $src_width * ( $dst_height / $src_height );
        $dst_x = ( $dst_width - $dst_w ) / 2;
    } elseif ( ($dst_width / $dst_height - $src_width / $src_height) < 0 ) {
        $dst_h = $src_height * ( $dst_width / $src_width );
        $dst_y = ( $dst_height - $dst_h ) / 2;
    }
*/
    imagecopyresampled($dstimg, $srcimg, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $src_width, $src_height);

    // 保存格式
    $arr = array(
        'jpg' => 'imagejpeg',
        'jpeg' => 'imagejpeg',
        'png' => 'imagepng',
        'gif' => 'imagegif',
        'bmp' => 'imagebmp'
    );
    $suffix = array_reverse(explode('.', $dstimage )) ;
    $suffix = $suffix[0];
    if (!in_array($suffix, array_keys($arr)) ) {
        return -2;
        exit;
    } else {
        eval( $arr[$suffix] . '($dstimg, "'.$dstimage.'");' );
    }

    imagejpeg($dstimg, $dstimage);

    imagedestroy($dstimg);
    imagedestroy($srcimg);

    return 1;

}

function getcreatemethod( $file ) {
    $arr = array(
        '474946' => "imagecreatefromgif('$file')",
        'FFD8FF' => "imagecreatefromjpeg('$file')",
        '424D' => "imagecreatefrombmp('$file')",
        '89504E' => "imagecreatefrompng('$file')"
    );
    $fd = fopen( $file, "rb" );
    $data = fread( $fd, 3 );

    $data = str2hex( $data );

    if ( array_key_exists( $data, $arr ) ) {
        return $arr[$data];
    } elseif ( array_key_exists( substr($data, 0, 4), $arr ) ) {
        return $arr[substr($data, 0, 4)];
    } else {
        return false;
    }
}

function str2hex( $str ) {
    $ret = "";

    for( $i = 0; $i < strlen( $str ) ; $i++ ) {
        $ret .= ord($str[$i]) >= 16 ? strval( dechex( ord($str[$i]) ) )
            : '0'. strval( dechex( ord($str[$i]) ) );
    }

    return strtoupper( $ret );
}

// BMP 创建函数  php本身无
function imagecreatefrombmp($filename)
{
    if (! $f1 = fopen($filename,"rb")) return FALSE;

    $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
    if ($FILE['file_type'] != 19778) return FALSE;

    $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'. '/Vcompression/Vsize_bitmap/Vhoriz_resolution'. '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));

    $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);

    if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
    $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
    $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
    $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
    $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
    $BMP['decal'] = 4-(4*$BMP['decal']);

    if ($BMP['decal'] == 4) $BMP['decal'] = 0;

    $PALETTE = array();
    if ($BMP['colors'] < 16777216)
    {
        $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
    }

    $IMG = fread($f1,$BMP['size_bitmap']);
    $VIDE = chr(0);

    $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
    $P = 0;
    $Y = $BMP['height']-1;
    while ($Y >= 0)
    {
        $X=0;
        while ($X < $BMP['width'])
        {
            if ($BMP['bits_per_pixel'] == 24)
                $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
            elseif ($BMP['bits_per_pixel'] == 16)
            {
                $COLOR = unpack("n",substr($IMG,$P,2));
                $COLOR[1] = $PALETTE[$COLOR[1]+1];
            }
            elseif ($BMP['bits_per_pixel'] == 8)
            {
                $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
                $COLOR[1] = $PALETTE[$COLOR[1]+1];
            }
            elseif ($BMP['bits_per_pixel'] == 4)
            {
                $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
                if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
                $COLOR[1] = $PALETTE[$COLOR[1]+1];
            }
            elseif ($BMP['bits_per_pixel'] == 1)
            {
                $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
                if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
                elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
                elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
                elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
                elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
                elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
                elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
                elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
                $COLOR[1] = $PALETTE[$COLOR[1]+1];
            }
            else
                return FALSE;
            imagesetpixel($res,$X,$Y,$COLOR[1]);
            $X++;
            $P += $BMP['bytes_per_pixel'];
        }
        $Y--;
        $P+=$BMP['decal'];
    }
    fclose($f1);

    return $res;
}
// BMP 保存函数，php本身无
function imagebmp ($im, $fn = false)
{
    if (!$im) return false;

    if ($fn === false) $fn = 'php://output';
    $f = fopen ($fn, "w");
    if (!$f) return false;

    $biWidth = imagesx ($im);
    $biHeight = imagesy ($im);
    $biBPLine = $biWidth * 3;
    $biStride = ($biBPLine + 3) & ~3;
    $biSizeImage = $biStride * $biHeight;
    $bfOffBits = 54;
    $bfSize = $bfOffBits + $biSizeImage;

    fwrite ($f, 'BM', 2);
    fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));

    fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));

    $numpad = $biStride - $biBPLine;
    for ($y = $biHeight - 1; $y >= 0; --$y)
    {
        for ($x = 0; $x < $biWidth; ++$x)
        {
            $col = imagecolorat ($im, $x, $y);
            fwrite ($f, pack ('V', $col), 3);
        }
        for ($i = 0; $i < $numpad; ++$i)
            fwrite ($f, pack ('C', 0));
    }
    fclose ($f);
    return true;
}
/**
 * 友好的时间显示
 *
 * @param int    $sTime 待显示的时间
 * @param string $type  类型. normal | mohu | full | ymd | other
 * @param string $alt   已失效
 * @return string
 */
function friendlyDate($sTime,$type = 'normal') {
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $sTime        =    strtotime($sTime);
    $cTime        =    time();
    $dTime        =    $cTime - $sTime;
    $dDay        =    intval(date("z",$cTime)) - intval(date("z",$sTime));
    //$dDay        =    intval($dTime/3600/24);
    $dYear        =    intval(date("Y",$cTime)) - intval(date("Y",$sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if($type=='normal'){
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
            //今天的数据.年份相同.日期相同.
        }elseif( $dYear==0 && $dDay == 0  ){
            //return intval($dTime/3600)."小时前";
            return '今天'.date('H:i',$sTime);
        }elseif($dYear==0){
            return date("m月d日 H:i",$sTime);
        }else{
            return date("Y-m-d H:i",$sTime);
        }
    }elseif($type=='mohu'){
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif( $dDay > 0 && $dDay<=7 ){
            return intval($dDay)."天前";
        }elseif( $dDay > 7 &&  $dDay <= 30 ){
            return intval($dDay/7) . '周前';
        }elseif( $dDay > 30 ){
            return intval($dDay/30) . '个月前';
        }
        //full: Y-m-d , H:i:s
    }elseif($type=='full'){
        return date("Y-m-d , H:i:s",$sTime);
    }elseif($type=='ymd'){
        return date("Y-m-d",$sTime);
    }else{
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif($dYear==0){
            return date("Y-m-d H:i:s",$sTime);
        }else{
            return date("Y-m-d H:i:s",$sTime);
        }
    }
}

/**
+----------------------------------------------------------
 * 功能：计算文件大小
+----------------------------------------------------------
 * @param int $bytes
+----------------------------------------------------------
 * @return string 转换后的字符串
+----------------------------------------------------------
 */
function byteFormat($bytes) {
    if($bytes <= 0){
        return 0;
    }

    $sizetext = array(" B", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    return round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), 2) . $sizetext[$i];
}